import rospy
import cv2
import numpy as np
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
hsv_low=np.array([103,146,0])
hsv_high=np.array([179,255,141])


def image_callback(msg):
    global flag,cv_img
    flag=True
    bridge = CvBridge()
    cv_img = bridge.imgmsg_to_cv2(msg, "bgr8")

if __name__ == '__main__':
    flag=False
    cv_img=np.zeros((640,480))
    rospy.init_node("image_subscriber")
    rospy.Subscriber("camera/color/image_raw", Image, image_callback)
    while not rospy.is_shutdown():
        if flag==True:
            cv2.imshow("image", cv_img)
            img_HSV=cv2.cvtColor(cv_img,cv2.COLOR_BGR2HSV)
            kernel_4=np.ones((4,4),np.uint8)
            mask=cv2.inRange(img_HSV,hsv_low,hsv_high)
            erosion=cv2.erode(mask,kernel_4,iterations=1)
            erosion=cv2.erode(erosion,kernel_4,iterations=1)
            dilation=cv2.dilate(erosion,kernel_4,iterations=1)
            dilation=cv2.dilate(dilation,kernel_4,iterations=1)

            target=cv2.bitwise_and(cv_img,cv_img,mask=dilation)
            ret,binary=cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)
            contours,hierarchy=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
            height = cv_img.shape[0]
            width = cv_img.shape[1]
            if len(contours) >0:
                x,y,w,h=cv2.boundingRect(contours[-1])
                print(w*h)
                cv2.rectangle(cv_img,(x,y),(x+w,y+h),(0,255),3)
                
            cv2.waitKey(1)
    
